package controllers

import (
	"time"
	models "yun/Models"

	"github.com/gin-gonic/gin"
)

type ApiIndexController struct {
	ApiBaseController
}
type User struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

func (a ApiIndexController) Adduser(c *gin.Context) {
	var thisuser User
	if err := c.BindJSON(&thisuser); err != nil {
		c.JSON(200, gin.H{"msg": "请使用JSON请求头", "code": "0"})
		return
	}
	name := thisuser.Name
	password := thisuser.Password
	if name == "" {
		c.JSON(200, gin.H{
			"msg":  "请填写账号名称",
			"code": "0",
		})
		return
	}
	if password == "" {
		c.JSON(200, gin.H{
			"msg":  "请填写账号密码",
			"code": "0",
		})
		return
	}
	// 加密
	password = a.encryptMD5(password)
	token := a.generateRandomString(12)
	user := models.User{}
	add := map[string]interface{}{
		"Name":     name,
		"Password": password,
		"AddTime":  time.Now().Unix(),
		"Token":    token,
	}
	have := db.Where("Name = ?", name).Find(&user)
	if have.RowsAffected > 0 {
		c.JSON(200, gin.H{
			"msg":  "当前用户名已存在~",
			"code": "0",
		})
		return
	}
	res := db.Model(&user).Create(add)
	if res.RowsAffected > 0 {
		c.JSON(200, gin.H{
			"msg":  "创建成功",
			"code": "1",
		})
	} else {
		c.JSON(200, gin.H{
			"msg":  "创建失败",
			"code": "0",
		})
	}

}

// 获取token,登录
func (a ApiIndexController) Login(c *gin.Context) {
	var thisuser User
	if err := c.BindJSON(&thisuser); err != nil {
		c.JSON(200, gin.H{"msg": "请使用JSON请求头", "code": "0"})
		return
	}
	name := thisuser.Name
	password := thisuser.Password
	password = a.encryptMD5(password)
	user := models.User{}
	find := map[string]interface{}{
		"Name":     name,
		"Password": password,
	}
	res := db.Find(&user, find)
	if res.RowsAffected > 0 {
		c.JSON(200, gin.H{
			"data": user,
			"code": "1",
		})
	} else {
		c.JSON(200, gin.H{
			"msg":  "用户信息错误",
			"code": "0",
		})
	}
}
